package com.example.questionnaire.utils;

import com.example.questionnaire.MyApplication;

import org.apache.cordova.common.CommonPlugin;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.net.UnknownHostException;

/**
 * author: liweixing
 * date: 2018/1/10
 */

public class UDPUtils {

    public static String encodType = "gb2312";

    /**
     * 发送UDP指令
     *
     * @param messageStr 要发送的信息
     * @param type       要发送的屏幕类型  1：大屏； 2：弹幕
     */
    public static void sendMessage(final String messageStr, int type) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                String udp_ip = "";
                String udp_port = "";
                if (type == 1) {
                    udp_ip = PrefUtils.getString(CommonPlugin.BIG_SCREEN_IP, "172.18.34.255");
                    udp_port = PrefUtils.getString(CommonPlugin.BIG_SCREEN_PORT, "8080");
                } else {
                    udp_ip = PrefUtils.getString(CommonPlugin.BARRAGE_IP, "172.18.34.105");
                    udp_port = PrefUtils.getString(CommonPlugin.BARRAGE_PORT, "8080");
                }

                //UDP不保证你收到，收到没有收到没有关系
                try {
                    //1,创建发送端Socket对象
                    DatagramSocket ds = new DatagramSocket();

                    //2,创建数据，并把数据打包
                    //调用Socket对象的发送方法发送数据包
                    byte[] bys = messageStr.getBytes(encodType);
                    //长度
                    int length = bys.length;
                    //IP地址对象
//                  String ipAddress = getIPAddress(this);
                    InetAddress address = InetAddress.getByName(udp_ip);
                    //端口（可以自己定义）
                    int port = Integer.parseInt(udp_port);
                    DatagramPacket dp = new DatagramPacket(bys, length, address, port);
                    ds.send(dp);
                    showToast("已发送");
                    //3，释放资源
                    ds.close();
                } catch (SocketException e) {
                    e.printStackTrace();
                    showToast(e.toString());
                } catch (UnknownHostException e) {
                    e.printStackTrace();
                    showToast(e.toString());
                } catch (IOException e) {
                    e.printStackTrace();
                    showToast(e.toString());
                } catch (Exception e) {
                    e.printStackTrace();
                    showToast(e.toString());
                }
            }
        }).start();
    }

    private static void showToast(final String message) {
        LogUtils.i("UDPUtils", "---00 " + message);
    }
}
